﻿namespace UnityEditor.Controls.InspectorControl
{
    using System;
    using System.ComponentModel;
    using System.Linq.Expressions;
    using UnityEngine.Core;

    public class InspectorItem : INotifyPropertyChanged
    {
        private GameObject gameObject;

        public InspectorItem(GameObject gameObject)
        {
            this.GameObject = gameObject;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public GameObject GameObject
        {
            get
            {
                return this.gameObject;
            }
            set
            {
                this.gameObject = value;
            }
        }

        public string Name
        {
            get
            {
                return this.GameObject.Name;
            }

            set
            {
                this.GameObject.Name = value;
                this.NotifyPropertyChanged(() => this.Name);
            }
        }

        public void NotifyPropertyChanged<TProperty>(Expression<Func<TProperty>> property)
        {
            var lambda = (LambdaExpression)property;
            MemberExpression memberExpression;
            if (lambda.Body is UnaryExpression)
            {
                var unaryExpression = (UnaryExpression)lambda.Body;
                memberExpression = (MemberExpression)unaryExpression.Operand;
            }
            else
                memberExpression = (MemberExpression)lambda.Body;
            this.OnPropertyChanged(memberExpression.Member.Name);
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
